extends layout

block content
  link(rel='stylesheet', href='/stylesheets/index.css')
  //- link(rel='stylesheet', href='/stylesheets/lib/jquery.highlight-within-textarea.css')
  //- script(src='/javascripts/lib/jquery.highlight-within-textarea.js')
  script(src='https://cdn.plot.ly/plotly-latest.min.js')
  script(src='https://code.jquery.com/jquery-3.2.1.min.js')
  script(src='https://cdnjs.cloudflare.com/ajax/libs/jquery.form/4.2.2/jquery.form.min.js')
  div(class='page')
    div(class="container")
      div(class="row")
        div(class="col-lg-6")
          form(role="form")
            div(class="form-group editorArea")
              h4(class='editor-title') Editor
                p(style='float: right; margin: 5px 5px 5px 5px; font-size: 15px;') First time? Read the 
                  a(href='#') tutorial
                  | &nbsp!
              textarea(class="form-control", spellcheck='false', id="netlist", rows="17", style='border: 2px solid #000000; border-radius: 5px;')
                //- Example file
                | *** RF switch circuit ***
                | * Author: Xing GUO
                | * Example file
                | * Input source
                | vs 1 0 dc 0V ac 1V sin(0V 1V 100MegHz 20ns 0)
                | Rs in 1 50ohm
                |
                | * Switch
                | Ci in 4 1.6nF
                | Rb 4 3 2.1k
                | Lc1 3 2 100uH
                | D1 4 50 diode
                | vmeter 50 5 dc 0
                | Lc2 5 0 100uH
                | cout 5 out 1.6n
                |
                | * Load
                | Rload out 0 1k
                |
                | * DC biasing
                | vcc 2 0 5V
                |             
                | .model diode d (is=1e-15A n=1)
                |
                | .tran .1ns 100ns
                |
                | * Please do not remove this line
                | .control
                |   run
                | .endc
                | .end
              div(class='warning-wrapper')
                div(class='warning-wrapper')
                  strong(class='warning') ⚠️ Warning: Your data will be cleared after closing this page...
                button(id='save-netlist', style='color: #ffffff; border: none', class='btn-link')
                  span(class="badge badge-warning badge-pill") Press me
                strong to save Netlist
        div(class='plot-edge', id='plot-edge', style='margin-top: 35px; width: 500px; height: 465px; border: 2px solid #000000; border-radius: 5px;')
          div(class="plot", id="plot", style='margin: 10px 10px 10px 10px;')
      div(class='row')
        div(class='col-lg-6')
          h4(class='option-title') Plot Option
          textarea(class="form-control", id="plot_option", spellcheck='false', rows="3", style='border: 2px solid #000000; border-radius: 5px;') 
            | [{"name": "v(in)", "curve": "v(in)"}, 
            |  {"name": "v(4,5)", "curve": "v(4,5)"},
            |  {"name": "v(out)", "curve": "v(out)"}]
          div(class="buttonArea input-group")
            button(id="run-code", class="btn btn-success input-group-btn", style='margin: 5px 5px 5px; width: 120px;') Run Code
            form(id='file-form', enctype="multipart/form-data", method="post", action='/upload', name="file-form")
              label(for='select-file', class='btn btn-success', style='margin: 5px 5px 5px; display: inline-block; width: 120px;') Select Lib
                input(id='select-file', type="file", name='lib', class="form-control-file", style='display: none;', onchange='handleFiles(this.files[0])')
              input(id='upload-button', type='submit', class='btn btn-success input-group-btn', style='margin: 5px 5px 5px; width: 120px;', value='Upload Lib')
            button(id="clear-plot", class="btn btn-danger input-group-btn", style='margin: 5px 5px 5px; width: 120px;') Clear Plots
        div(class='terminal', style='width: 500px;')
          //- div(class='terminal', style='width=600px')
          //-   h4(class='terminal-title') Info Area
          h4(class='terminal-title', style='margin-top: 10px;') Terminal Output
          div(class='terminal-edge', style='border: 2px solid #000000; border-radius: 5px;')
            div(id='terminal', class='terminal-text-area', style='margin-top: 5px; margin-bottom: 5px; margin-right: 5px;margin-left: 5px; height:130px; overflow:auto;')
              div(class='initial-info')
                span(class='badge badge-success') success
                span &nbsp;
                span Server message will be displayed here :)
          
  //- scripts
  script(src='/socket.io/socket.io.js')
  - let socket_url = socket_conf;
  //- socket things
  script.
    let socket = io.connect('#{socket_url}');
    // connect succeed
    socket.on('loading-page', function (data) {
      socket.emit('socket-id', { socket_id: socket.id });
    });

  script.
    // create terminal msg
    function createTerminalMSG(data) {
      let div = document.createElement('div');
      let badge = document.createElement('span');
      let text = '';
      if (data.type == 'success') {
        text = document.createTextNode(' success ');
        badge.className = 'badge badge-success';
      } else if (data.type == 'info') {
        text = document.createTextNode(' info ');
        badge.className = 'badge badge-info';
      } else if (data.type == 'error') {
        text = document.createTextNode(' error ');
        badge.className = 'badge badge-danger';
      }
      badge.appendChild(text);
      div.appendChild(badge);
      let blank = document.createElement('span');
      text = document.createTextNode(' ');
      div.appendChild(text);
      let msg = document.createElement('span');
      text = document.createTextNode(data.msg);
      div.appendChild(text);
      terminal.appendChild(div);
      terminal.scrollTop = terminal.scrollHeight;
    }
    
  script.
    // upload-btn ajax
    $(function() {            
      $('#file-form').ajaxForm({                 
        beforeSubmit: handleFiles,
        success: SubmitSuccesful,
        error: AjaxError                               
      });
    });

    function AjaxError() {
      createTerminalMSG({ type: 'error', msg: 'Oops! Unknown error! Refresh your page' });
    }

    function SubmitSuccesful(response, status) {        
      createTerminalMSG(response);
    }
    
    function handleFiles(file, jqForm, options) {
      let data = {};
      if (file.type != 'text/plain' && !jqForm && !options) {
        data = {
          type: 'error',
          msg: 'Please upload a text file which end up with ".txt"'
        }
        createTerminalMSG(data);
        // remove input file
      } else if (file.type == 'text/plain' && !jqForm && !options) {
        data = {
          type: 'success',
          msg: 'Great! You could upload: ' + file.name
        }
        createTerminalMSG(data);
      }
    }
  script.
    // button callback event
    let netlist_content = document.getElementById('netlist');
    let plot_option_content = document.getElementById('plot_option');
    let submit_button = document.getElementById('run-code');
    let save_netlist_button = document.getElementById('save-netlist');
    let clear_plot_button = document.getElementById('clear-plot');
    
    // submit_button callback
    submit_button.addEventListener('click', () => {
      let netlist = netlist_content.value;
      let plot_option = plot_option_content.value
      socket.emit('netlist-data', { socket_id: socket.id, netlist: netlist, plot_option: plot_option });
    });
    
    // save_netlist_button callback
    save_netlist_button.addEventListener('click', () => {
      // do nothing
      var textToWrite = document.getElementById('netlist').value;
      var textFileAsBlob = new Blob([textToWrite], {type:'text/plain'});
      var fileNameToSaveAs = socket.id + '-netlist.txt';

      var downloadLink = document.createElement("a");
      downloadLink.download = fileNameToSaveAs;
      downloadLink.innerHTML = "Download File";
      if (window.webkitURL != null) {
          // Chrome allows the link to be clicked
          // without actually adding it to the DOM.
          downloadLink.href = window.webkitURL.createObjectURL(textFileAsBlob);
      }
      else {
          // Firefox requires the link to be added to the DOM
          // before it can be clicked.
          downloadLink.href = window.URL.createObjectURL(textFileAsBlob);
          downloadLink.onclick = downloadLink.remove();
          downloadLink.style.display = "none";
          document.body.appendChild(downloadLink);
      }
      downloadLink.click();
    });
    
    // clear_plot_button callback
    clear_plot_button.addEventListener('click', () => {
      Plotly.purge('plot');
    });
    
  script.
    // display server message
    socket.on('server-msg', (data) => {
      let terminal = document.getElementById('terminal');
      createTerminalMSG(data);
    });
    
  //- plotly.js things
  script.
    let colors = ['rgb(148, 0, 211)', 'rgb(255, 127, 0)', 'rgb(0, 0, 255)', 
                  'rgb(255, 0 , 0)', 'rgb(255, 255, 0)', 'rgb(75, 0, 130)',
                  'rgb(0, 255, 0)'];
    let layout = {
      autosize: false,
      width: 465,
      height: 435,
      margin: {
        l: 30,
        r: 20,
        b: 80,
        t: 80
      }
    };
    socket.on('netlist-data', (data) => {
      
      // plot graph
      let traces = [];
      let curve_names = {};
      for (var i = 0; i < data.curves.length; i ++) {
        let showLegend = false;
        if (!curve_names[data.label_info[data.curves[i].belong_to]]) {
          showLegend = true;
          curve_names[data.label_info[data.curves[i].belong_to]] = 1;
        }
        
        traces.push({ 
          x: data.curves[i].x, 
          y: data.curves[i].y, 
          connectgaps: false, 
          showlegend: showLegend,
          name: data.label_info[data.curves[i].belong_to],
          marker: {color: colors[data.curves[i].belong_to]}
        });
      }
      Plotly.newPlot('plot', traces, layout);
    });
    
